import {
	autoLogin,
	runLogin
} from "@/api/mbti"

import store from "@/store/index.js"
import storage from "@/utils/storage";

function handleGetLoginCode() {
	return new Promise((resolve, reject) => {
		uni.login({
			success: (res) => {
				if (res.errMsg === "login:ok") {
					resolve(res.code)
				}
			},
			fail: (err) => {
				uni.showToast({
					title: "登录失败",
					icon: 'none'
				})
				// console.log("登录失败");
				resolve(null)
			}

		})
	})
}

function login(hideLoading = false) {
	return new Promise((resolve, reject) => {
		if (!hideLoading) {
			// uni.showLoading()
		}
		handleGetLoginCode().then(code => {
			runLogin({
				code
			}).then(res => {
				uni.hideLoading()
				let data = res.data
				let {
					token,
					hasRegister,
					user
				} = data
				if (token) {
					let accessToken = "Bearer " + token
					storage.setAccessToken(accessToken)
				} else {
					storage.setAccessToken(null)
				}

				if (user) {
					store.commit('updateUerInfo', user)
				} else {
					store.commit('updateUerInfo', null)
				}
				console.log("用户信息是", data)

				resolve(data)


			}).catch(err => {
				uni.hideLoading()
				uni.showToast({
					title: "登录接口异常",
					icon: "none"
				})
				reject({
					tip: "登录接口异常"
				})
			})
		}).catch(err => {
			uni.hideLoading()
			uni.showToast({
				title: "码获取失败",
				icon: "none"
			})
			reject({
				tip: "code码获取失败"
			})
		})
	})


}



export {
	login,
	handleGetLoginCode
}